import { Injectable, Logger } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config';
import { plainToInstance } from 'class-transformer';
// dtos
import { LoginOutputDto } from './dtos';
// user.service
import { UserService } from '../system/user/user.service';

@Injectable()
export class AuthService {
  // logger
  readonly logger = new Logger(AuthService.name);
  constructor(
    private readonly configService: ConfigService,
    private readonly jwtService: JwtService,
    private readonly userService: UserService,
  ) {}
  /**
   * 登录取得token
   * @param user 用户从请求上下文来
   * @param ip ip地址
   */
  async login(user: any, ip?: string): Promise<LoginOutputDto> {
    this.logger.debug('user', JSON.stringify(user));
    /** 这里一定要username, casbin authz里面要用 **/
    const payload = {
      sub: user.id,
      username: user.username,
      ip,
      t: Date.now(),
    };
    this.logger.debug('ip', ip);
    this.logger.debug('payload', payload);
    const authToken = {
      token: this.jwtService.sign(
        { ...payload },
        {
          secret: this.configService.get<string>('jwt.secret_key'),
          expiresIn: '7d',
        },
      ),
      refresh_token: this.jwtService.sign(payload, {
        secret: this.configService.get<string>('jwt.secret_key'),
        expiresIn: '30d',
      }),
    };
    this.logger.debug('authToken', authToken);
    return plainToInstance(LoginOutputDto, authToken, {
      excludeExtraneousValues: true,
    });
  }
}
